const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const { FFMPEG_PATH } = require("../src/utils/ffmpeg");
if (1 < 2) {
  console.log("  为谨慎期间，请确认确实需要重新运行此脚本...");
  process.exit(1);
}
// 源目录和目标目录
const sourceDir = path.join("input", "gamestolearnenglish", "DesertDrag");
const targetDir = path.join("input", "gamestolearnenglish", "DesertDrag", "Sorted");

// 确保目标目录存在
if (!fs.existsSync(targetDir)) {
  fs.mkdirSync(targetDir, { recursive: true });
}

// 读取符号映射文件
const symbolsFile = path.join(sourceDir, "symbolClass", "symbols.csv");
const symbolsData = fs.readFileSync(symbolsFile, "utf8");

// 解析符号映射数据
const symbolMap = {}; // id -> name
const symbolMapReverse = {}; // name -> id
const lines = symbolsData.split("\n");
lines.forEach(line => {
  if (line.trim() !== "") {
    const [id, name] = line.split(";");
    symbolMap[id] = name;
    // 使用小写名称作为键以便不区分大小写的匹配
    symbolMapReverse[name.toLowerCase()] = id;
  }
});

// 创建一个映射来存储组信息
const groupMap = {};

// 处理脚本文件以查找关联关系
const scriptsDir = path.join(sourceDir, "scripts");
const scriptFiles = fs.readdirSync(scriptsDir);

// 查找s_开头的脚本文件（音频相关）
scriptFiles.forEach(file => {
  if (file.startsWith("s_") && file.endsWith(".as")) {
    const content = fs.readFileSync(path.join(scriptsDir, file), "utf8");
    // 提取组名（两个下划线之间的内容）
    const match = file.match(/s_([^_]+)_(\d+)/);
    if (match) {
      const groupName = match[1];
      const itemNumber = match[2];

      // 在内容中查找symbol引用
      const symbolMatch = content.match(/symbol(\d+)/);
      if (symbolMatch) {
        const symbolId = symbolMatch[1];

        if (!groupMap[groupName]) {
          groupMap[groupName] = [];
        }

        groupMap[groupName].push({
          number: itemNumber,
          audioSymbolId: symbolId,
          scriptFile: file,
        });
      }
    }
  }
});

// 处理mc_开头的脚本文件（图形相关）
const mcMap = {};
scriptFiles.forEach(file => {
  if (file.startsWith("mc_") && file.endsWith(".as")) {
    const content = fs.readFileSync(path.join(scriptsDir, file), "utf8");
    // 提取组名（两个下划线之间的内容）
    const match = file.match(/mc_([^_]+)_(\d+)/);
    if (match) {
      const groupName = match[1];
      const itemNumber = match[2];

      // 在内容中查找symbol引用
      const symbolMatch = content.match(/symbol(\d+)/);
      if (symbolMatch) {
        const symbolId = symbolMatch[1];

        if (!mcMap[groupName]) {
          mcMap[groupName] = {};
        }

        mcMap[groupName][itemNumber] = {
          symbolId: symbolId,
          scriptFile: file,
        };
      }
    }
  }
});

// 处理sprites目录中的PNG文件
const spritesDir = path.join(sourceDir, "sprites");
const spriteDirs = fs.readdirSync(spritesDir);

// 创建PNG映射：groupName -> itemNumber -> pngPath
const pngMap = {};
spriteDirs.forEach(dir => {
  // 解析目录名，提取组名和项目编号
  const match = dir.match(/DefineSprite_\d+_mc_([^_]+)_(\d+)/);
  if (match) {
    const groupName = match[1];
    const itemNumber = match[2];

    if (!pngMap[groupName]) {
      pngMap[groupName] = {};
    }

    const pngPath = path.join(spritesDir, dir, "1.png");
    if (fs.existsSync(pngPath)) {
      pngMap[groupName][itemNumber] = pngPath;
    }
  }
});

// 创建SVG映射：通过扫描shapes目录中的文件，查找包含特定symbol ID的SVG文件
const shapesDir = path.join(sourceDir, "shapes");
const svgFiles = fs.readdirSync(shapesDir);

// 创建SVG映射：symbolId -> svgFileName
const svgMap = {};
svgFiles.forEach(svgFile => {
  if (svgFile.endsWith(".svg")) {
    const svgPath = path.join(shapesDir, svgFile);
    const svgContent = fs.readFileSync(svgPath, "utf8");

    // 查找SVG文件中包含的symbol ID（通过检查ffdec:objectType="shape"的元素）
    const symbolMatch = svgContent.match(/id="(\d+)"/);
    if (symbolMatch) {
      const symbolId = symbolMatch[1];
      svgMap[symbolId] = svgFile;
    }
  }
});

// 读取文本文件
const textFile = path.join(sourceDir, "scripts", "com", "opd", "classes", "res", "txt", "txtEngGrp.as");
const textContent = fs.readFileSync(textFile, "utf8");

// 解析文本内容
const textMap = {};
const textLines = textContent.split("\n");
textLines.forEach(line => {
  const match = line.match(/public static var rText_(\w+):\* = "([^"]*)";/);
  if (match) {
    const groupName = match[1];
    const words = match[2].split(";").filter(word => word.length > 0);
    textMap[groupName.toLowerCase()] = words;
  }
});

// 解析所有choices文件以获取组封面图映射
const choicesFiles = scriptFiles.filter(file => file.startsWith("choicesSet") && file.endsWith(".as"));
const groupToChoiceMap = {};

choicesFiles.forEach(file => {
  const content = fs.readFileSync(path.join(scriptsDir, file), "utf8");
  const lines = content.split("\n");
  lines.forEach(line => {
    const match = line.match(/public var (\w+):(\w+);/);
    if (match) {
      const groupName = match[1];
      const choiceName = match[2];
      // 将组名转换为小写以实现不区分大小写的匹配
      groupToChoiceMap[groupName.toLowerCase()] = choiceName.toLowerCase();
    }
  });
});

// 根据组创建目录并复制文件
Object.keys(groupMap).forEach(groupName => {
  const groupDir = path.join(targetDir, groupName);
  if (!fs.existsSync(groupDir)) {
    fs.mkdirSync(groupDir, { recursive: true });
  }

  // 处理该组中的每个项目
  groupMap[groupName].forEach(item => {
    // 获取单词名称
    let wordName = "";
    if (textMap[groupName.toLowerCase()] && textMap[groupName.toLowerCase()][parseInt(item.number)]) {
      wordName = textMap[groupName.toLowerCase()][parseInt(item.number)];
      // 将文件名中的特殊字符替换为下划线
      wordName = wordName.replace(/[\/\\:*?"<>|]/g, "_");
    } else {
      // 如果找不到对应单词，则使用数字命名
      wordName = item.number;
    }

    // 查找对应的FLV文件
    const soundFiles = fs.readdirSync(path.join(sourceDir, "sounds"));
    const flvFile = soundFiles.find(f => f.startsWith(`${item.audioSymbolId}_`));

    // 复制并转换FLV文件为WAV（如果找到）
    if (flvFile) {
      const srcPath = path.join(sourceDir, "sounds", flvFile);
      const destPath = path.join(groupDir, `${wordName}.wav`);
      try {
        // 使用FFmpeg将FLV转换为WAV，添加更多参数确保元数据完整
        const command = `"${FFMPEG_PATH}" -i "${srcPath}" -acodec pcm_s16le -ar 16000 -ac 1 -fflags +genpts -y "${destPath}"`;
        execSync(command, { stdio: "ignore" });
        console.log(`Converted ${flvFile} to ${groupName}/${wordName}.wav`);
      } catch (err) {
        console.error(`Error converting ${flvFile}:`, err.message);
      }
    }

    // 查找对应的SVG文件
    const mcInfo = mcMap[groupName] ? mcMap[groupName][item.number] : null;
    let svgFileName = null;
    if (mcInfo) {
      // 根据符号ID查找对应的SVG文件
      svgFileName = svgMap[mcInfo.symbolId];
    }

    // 复制SVG文件（如果找到）
    if (svgFileName) {
      const srcPath = path.join(sourceDir, "shapes", svgFileName);
      const destPath = path.join(groupDir, `${wordName}.svg`);
      try {
        fs.copyFileSync(srcPath, destPath);
        console.log(`Copied ${svgFileName} to ${groupName}/${wordName}.svg`);
      } catch (err) {
        console.error(`Error copying ${svgFileName}:`, err.message);
      }
    } else {
      console.log(`Could not find SVG for ${groupName}/${wordName}`);
    }

    // 复制PNG文件（如果找到）
    if (pngMap[groupName] && pngMap[groupName][item.number]) {
      const srcPath = pngMap[groupName][item.number];
      const destPath = path.join(groupDir, `${wordName}.png`);
      try {
        fs.copyFileSync(srcPath, destPath);
        console.log(`Copied PNG to ${groupName}/${wordName}.png`);
      } catch (err) {
        console.error(`Error copying PNG for ${groupName}/${wordName}:`, err.message);
      }
    } else {
      console.log(`Could not find PNG for ${groupName}/${wordName}`);
    }
  });

  // 为该组添加封面图
  const choiceName = groupToChoiceMap[groupName.toLowerCase()];
  if (choiceName && choiceName !== "movieclip") {
    // 在symbols.csv中查找choice的ID（使用小写名称进行不区分大小写的匹配）
    const choiceId = symbolMapReverse[choiceName];
    if (choiceId) {
      // 在sprites目录中查找对应的封面图
      // 使用更灵活的匹配方式：以DefineSprite_开头，以choiceName结尾的目录
      let coverImagePath = null;
      for (const dir of spriteDirs) {
        if (dir.startsWith(`DefineSprite_${choiceId}_`) && dir.toLowerCase().endsWith(choiceName)) {
          const potentialPath = path.join(spritesDir, dir, "1.png");
          if (fs.existsSync(potentialPath)) {
            coverImagePath = potentialPath;
            break;
          }
        }
      }

      // 如果还没找到，尝试不区分大小写的模糊匹配
      if (!coverImagePath) {
        for (const dir of spriteDirs) {
          if (dir.toLowerCase().startsWith(`definesprite_${choiceId}_`) && dir.toLowerCase().endsWith(choiceName)) {
            const potentialPath = path.join(spritesDir, dir, "1.png");
            if (fs.existsSync(potentialPath)) {
              coverImagePath = potentialPath;
              break;
            }
          }
        }
      }

      if (coverImagePath) {
        const destPath = path.join(groupDir, "cover.png");
        try {
          fs.copyFileSync(coverImagePath, destPath);
          console.log(`Copied cover image for ${groupName} group`);
        } catch (err) {
          console.error(`Error copying cover image for ${groupName}:`, err.message);
        }
      } else {
        console.log(`Could not find cover image for ${groupName} group`);
      }
    } else {
      // 尝试直接在sprites目录中查找命名模式为DefineSprite_*_choiceName的目录
      let coverImagePath = null;
      for (const dir of spriteDirs) {
        if (dir.toLowerCase().endsWith(`_${choiceName}`)) {
          const potentialPath = path.join(spritesDir, dir, "1.png");
          if (fs.existsSync(potentialPath)) {
            coverImagePath = potentialPath;
            break;
          }
        }
      }

      if (coverImagePath) {
        const destPath = path.join(groupDir, "cover.png");
        try {
          fs.copyFileSync(coverImagePath, destPath);
          console.log(`Copied cover image for ${groupName} group using direct match`);
        } catch (err) {
          console.error(`Error copying cover image for ${groupName}:`, err.message);
        }
      } else {
        console.log(`Could not find symbol ID for choice ${choiceName}`);
      }
    }
  } else if (choiceName === "movieclip") {
    console.log(`Group ${groupName} is mapped to MovieClip, no cover image available`);
  } else {
    console.log(`Could not find choice name for group ${groupName}`);
  }
});

console.log("Resource organization completed.");
